package com.tamecode.flowable.spring.test;

import org.flowable.engine.*;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.spring.ProcessEngineFactoryBean;
import org.flowable.task.api.Task;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * @Author: Liqc
 * @Date: 2021/11/8 10:58
 */
public class FinancialReportStart {

    public static void main(String[] args) {
        // 获取spring的上下文
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "SpringTransactionIntegrationTest-context.xml");

        RepositoryService repositoryService = (RepositoryService) applicationContext.getBean("repositoryService");
        RuntimeService runtimeService = (RuntimeService) applicationContext.getBean("runtimeService");

        // 部署流程定义
        repositoryService.createDeployment()
                .addClasspathResource("/process/financialReport.bpmn20.xml")
                .deploy();

        // 启动流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("financialReport");

        TaskService taskService = applicationContext.getBean(TaskService.class);
        ProcessEngineFactoryBean processEngine = applicationContext.getBean(ProcessEngineFactoryBean.class);

        // 获取 accountancy 组的任务
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("accountancy").list();

        // take tasks by user，用户必须是 accountancy 组的，在流程中有定义
//        List<Task> tasks = taskService.createTaskQuery().taskCandidateUser("kermit").list();

        // 认领任务, 认领后，该组的其它成员将看不到些任务。需要先创建用户和角色
        Task task = tasks.get(1);
        taskService.claim(task.getId(), "fozzie");

        // 查询个人申领的任务
//        List<Task> tasks = taskService.createTaskQuery().taskAssignee("fozzie").list();

        // 会计师（accountancy组的成员）现在需要开始撰写财务报告了。完成报告后，他就可以完成任务（complete），代表任务的所有工作都已完成。
        taskService.complete(task.getId());


        // 通过 historyService 来验证流程是否结束
        HistoryService historyService = applicationContext.getBean(HistoryService.class);
        HistoricProcessInstance historicProcessInstance =
                historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("Process instance end time: " + historicProcessInstance.getEndTime());

    }

}
